package com.zw.hrm.service.impl;

import com.alibaba.fastjson.JSON;
import com.zw.hrm.constants.MQConstants;
import com.zw.hrm.domain.Pager;
import com.zw.hrm.feignclients.FastdfsFeignClient;
import com.zw.hrm.feignclients.RedisFeignClient;
import com.zw.hrm.mapper.PagerMapper;
import com.zw.hrm.mapper.SiteMapper;
import com.zw.hrm.service.IPagerService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.zw.hrm.util.AjaxResult;
import com.zw.hrm.util.MyFileUtils;
import com.zw.hrm.util.VelocityUtils;
import com.zw.hrm.util.ZipUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zw
 * @since 2020-02-26
 */
@Service
public class PagerServiceImpl extends ServiceImpl<PagerMapper, Pager> implements IPagerService {
    @Autowired
    private FastdfsFeignClient fastdfsFeignClient;
    @Autowired
    private RedisFeignClient redisFeignClient;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private SiteMapper siteMapper;


    //获取系统临时目录 ： C:\Users\ADMINI~1\AppData\Local\Temp\
    private String getTempDir(){
        String tempDir = System.getProperty("java.io.tmpdir");
        return tempDir;
    }

    @Override
    public void pageStatic(String pageName, String redisDataKey) throws Exception {

        //基本参数校验
        if (pageName.isEmpty() || redisDataKey.isEmpty()){
            throw new RuntimeException("参数异常，页面静态化失败");
        }

        //准备模板
        //下载模板
        Pager pager = baseMapper.selectByName(pageName);
        byte[] templateZipBytes = fastdfsFeignClient.download(pager.getTemplateUrl());
        if(templateZipBytes == null || templateZipBytes.length == 0){
            throw new RuntimeException("模板下载失败");
        }

        //把templateZipBytes写到磁盘 ：临时目录 , 要把“\” ,替换成 “/” , 不用，因为是自动获取的目录，不会有问题
        // C:\Users\51688\AppData\Local\Temp\
        String zipPath = getTempDir()+pageName+".zip";
        File file = MyFileUtils.createFile(zipPath);
        FileCopyUtils.copy(templateZipBytes,file);

        //解压模板
        String unZipPath = getTempDir() + "pagestatic/";
        ZipUtils.unZip(zipPath, unZipPath);

        //准备数据
        //从redis中拿数据
        AjaxResult ajaxResult = redisFeignClient.get(redisDataKey);
        if (!ajaxResult.isSuccess() || ajaxResult.getResultObj() == null){
            throw new RuntimeException("数据获取失败");
        }
        String dataString = ajaxResult.getResultObj().toString();
        Map<String,Object> model = JSON.parseObject(dataString, Map.class);

        //合并模板
        //数据model准备
        model.put("staticRoot", unZipPath);
        //模板路径,生成html路径
        String templatePath = unZipPath+pageName+".vm";
        String htmlPath = unZipPath+pageName+".html";
        VelocityUtils.staticByTemplate(model, templatePath, htmlPath);
        //上传html到fastdfs
        byte[] htmlBytes = FileCopyUtils.copyToByteArray(new File(htmlPath));
        AjaxResult htmlResult = fastdfsFeignClient.uploadBytes(htmlBytes, "html");
        if (!htmlResult.isSuccess() || htmlResult.getResultObj() == null){
            throw new RuntimeException("页面静态化失败，html上传失败");
        }
        //MQ发送消息
        HashMap<String,Object> mqMessage = new HashMap<>();
        mqMessage.put("htmlPathInFastdfs",htmlResult.getResultObj());
        mqMessage.put("physicalPath",pager.getPhysicalPath());

        //routingkey，对应站点的sn编码
        String routingKey =  siteMapper.selectById(pager.getSiteId()).getSn();

        rabbitTemplate.convertAndSend(MQConstants.NAME_EXCHANGE_PAGE_DIRECT, routingKey, JSON.toJSONString(mqMessage));
    }
}
